package com.atguigu.gulimall.order.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Configuration
public class GuliFeignConfig {

    /**
     * 解决fein远程调用丢失请求头
     * @return
     */
    @Bean("requestInterceptor")
    public RequestInterceptor requestInterceptor() {
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {
                // 1、RequestContextHolder 拿到当前的请求
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if (requestAttributes != null) {
                    System.out.println("添加cookie的RequestInterceptor线程。。。" + Thread.currentThread().getId());
                    // 获取老请求
                    HttpServletRequest request = requestAttributes.getRequest();
                    if (request != null){
                        // 获取老请求头的cookie
                        String cookie = request.getHeader("Cookie");
                        // 给feign新生成的请求模板添加cookie
                        requestTemplate.header("Cookie",cookie);
                    }
                }
            }
        };
    }
}
